<?php

namespace App\Foundation\Utils;

use Framework\Foundation\Database\FDB;

class TableUtil
{
    public static function getTableNames($database)
    {
        $sql = "SHOW TABLES";
        $pdo = FDB::getPdo();
        $statement = $pdo->query($sql);

        $tables = array();
        while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
            $virtualField = 'Tables_in_' . $database;
            $tables[] = $row[$virtualField];
        }

        return $tables;
    }

    public static function getTableField($db, $table)
    {
        $fields = [];
        $schema = self::getTableSchema($db, $table);
        foreach ($schema as $v) {
            // 表的所有字段
            $fields[$v['COLUMN_NAME']] = $v['DATA_TYPE'];
        }

        return $fields;
    }

    public static function getTableSchema($db, $table)
    {
//        $sql = "SELECT * FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA`='{$db}' AND `TABLE_NAME`='{$table}'";
//        $pdo = getPDO();
//        $statement = $pdo->query($sql);

        $sql2 = "SELECT * FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA`=? AND `TABLE_NAME`=?";
        $pdo = FDB::getPdo();
        $statement = $pdo->prepare($sql2);
        $statement->execute([$db, $table]);
        $ret = $statement->fetchAll(\PDO::FETCH_ASSOC);

        return $ret;
    }
}
